#因为不稳定，官方把API关闭了，所以暂时用不了
from lib.settings import BITBAYS_API_URL
from lib.utilBitbays import api, sort_and_format
import config


class Bitbays(object):
    def __init__(self):
        self.__url = BITBAYS_API_URL['host']  # url使用BITBAYS_API_URL['host']
        self.__apikey = config.BITBAYS_API_KEY
        self.__secretkey = config.BITBAYS_SECRET_TOKEN
        self.fee = BITBAYS_API_URL['fee']

        self.btc_free = 0.0  # 账户情况
        self.btc_frozen = 0.0
        self.cny_free = 0.0
        self.cny_frozen = 0.0

        self.bid = 0.0  # 买一卖一情况
        self.bid_volume = 0.0
        self.ask = 0.0
        self.ask_volume = 0.0

    def update_depth(self):
        try:
            response = api(BITBAYS_API_URL['depth'], '', False, self.__apikey, self.__secretkey)
            if not response:
                self.bid = 0.0
                self.bid_volume = 0.0
                self.ask = 0.0
                self.ask_volume = 0.0
                return False
            if response['status'] != 200:
                self.bid = 0.0
                self.bid_volume = 0.0
                self.ask = 0.0
                self.ask_volume = 0.0
                return False
            self.bid = float(sort_and_format(response['result']['bids'], True)[0]['price'])
            self.bid_volume = float(sort_and_format(response['result']['bids'], True)[0]['volume'])
            self.ask = float(sort_and_format(response['result']['asks'], False)[0]['price'])
            self.ask_volume = float(sort_and_format(response['result']['asks'], False)[0]['volume'])
            return True
        except Exception as e:
            print(e)
            self.bid = 0.0
            self.bid_volume = 0.0
            self.ask = 0.0
            self.ask_volume = 0.0
            return False



    def update_accountInfo(self):
        try:
            params = {}
            response = api(BITBAYS_API_URL['account_info'], params, True, self.__apikey, self.__secretkey)
            if not response:  # 如果更新账户信息出错，则将用户资产置为零，不允许交易
                self.btc_free = 0.0
                self.btc_frozen = 0.0
                self.cny_free = 0.0
                self.cny_frozen = 0.0
                return False

            if response['status'] != 200:
                self.btc_free = 0.0
                self.btc_frozen = 0.0
                self.cny_free = 0.0
                self.cny_frozen = 0.0
                return False

            self.btc_free = float(response['result']['wallet']['btc']['avail'])
            self.btc_frozen = float(response['result']['wallet']['btc']['lock'])
            self.cny_free = float(response['result']['wallet']['cny']['avail'])
            self.cny_frozen = float(response['result']['wallet']['cny']['lock'])
            return True

        except Exception as e:
            print(e.with_traceback())
            self.btc_free = 0.0
            self.btc_frozen = 0.0
            self.cny_free = 0.0
            self.cny_frozen = 0.0
            return False



    def buy(self, price, amount):
        try:
            params = {}
            params['market'] = 'btc_cny'
            params['op'] = 'buy'
            params['order_type'] = 0
            params['price'] = price
            params['amount'] = amount
            response = api(BITBAYS_API_URL['trade'], params, True, self.__apikey, self.__secretkey)
            if not response:
                return False
            if response['status'] != 200:
                return False
            return response['result']['id']

        except Exception as e:
            print(e)
            return False




    def sell(self, price, amount):
        try:
            params = {}
            params['market'] = 'btc_cny'
            params['op'] = 'sell'
            params['order_type'] = 0
            params['price'] = price
            params['amount'] = amount
            response = api(BITBAYS_API_URL['trade'], params, True, self.__apikey, self.__secretkey)
            if not response:
                return False
            if response['status'] != 200:
                return False
            return response['result']['id']

        except Exception as e:
            print(e)
            return False



    def order_info(self, orderId):
        try:
            if orderId == False:
                return False
            params = {}
            params['id'] = orderId
            response = api(BITBAYS_API_URL['order_info'], params, True, self.__apikey, self.__secretkey)
            if not response:
                return False
            if response['status'] != 200:
                return False
            if response['result']['status'] in (0, 1):
                return 'cancelable'
            else:
                return 'ircancelable'
        except Exception as e:
            print(e)
            return False



    def get_orders(self):
        try:
            params = {}
            params['market'] = 'btc_cny'
            params['status'] = 0
            response = api(BITBAYS_API_URL['order_info'], params, True, self.__apikey, self.__secretkey)
            if not response:
                return False
            if response['status'] != 200:
                return False
            return response['result']
        except Exception as e:
            print(e)
            return False




    def cancel_order(self, orderId):
        try:
            if orderId == False:
                return False
            params = {}
            params['market'] = orderId
            response = api(BITBAYS_API_URL['order_info'], params, True, self.__apikey, self.__secretkey)
            if not response:
                return False
            if response['status'] != 200:
                return False
            if response['result']=='ok':
                return True
            else:
                return False
        except Exception as e:
            print(e)
            return False




    def cancel_all(self):
        response = self.get_orders()

        if not response:
            return False

        for order in response:
            self.cancel_order(order['id'])


